﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using Microsoft.Win32;
using System.Configuration;

namespace CDDocumentExtractor
{
    public class WebUtility
    {
        public static string LogFileIfNoJudgement
        {
            get
            {
                return ConfigurationManager.AppSettings["LogFileIfNoJudgement"].ToString();
            }
        }

        public static string LogFile
        {
            get
            {
                return ConfigurationManager.AppSettings["LogFile"].ToString();
            }
        }

        public static string SourceFolder
        {
            get
            {
                return ConfigurationManager.AppSettings["SourceFolder"].ToString();
            }
        }

        public static string ArchieveFolder
        {
            get
            {
                return ConfigurationManager.AppSettings["ArchieveFolder"].ToString();
            }
        }

        public static string DocumentLogFile
        {
            get
            {
                return ConfigurationManager.AppSettings["DocumentLogFile"].ToString();
            }
        }

        public static string DocumentsFolder
        {
            get
            {
                return ConfigurationManager.AppSettings["DocumentsFolder"].ToString();
            }
        }

        public static string TempFile
        {
            get
            {
                return ConfigurationManager.AppSettings["TempFile"].ToString();
            }
        }

        #region Registry related methods...
        public static string Read(string KeyName)
        {
            // Opening the registry key
            RegistryKey rk = Registry.LocalMachine;
            // Open a subKey as read-only
            RegistryKey sk1 = rk.OpenSubKey("SOFTWARE\\InfoOne");
            // If the RegistrySubKey doesn't exist -> (null)
            if (sk1 == null)
            {
                return null;
            }
            else
            {
                try
                {
                    // If the RegistryKey exists I get its value
                    // or null is returned.
                    return (string)sk1.GetValue(KeyName.ToUpper());
                }
                catch (Exception e)
                {
                    return null;
                }
            }
        }
        public static bool Write(string KeyName, object Value)
        {
            try
            {
                // Setting
                RegistryKey rk = Registry.LocalMachine;
                // I have to use CreateSubKey 
                // (create or open it if already exits), 
                // 'cause OpenSubKey open a subKey as read-only
                RegistryKey sk1 = rk.CreateSubKey("SOFTWARE\\InfoOne");
                // Save the value
                sk1.SetValue(KeyName.ToUpper(), Value);

                return true;
            }
            catch (Exception e)
            {
                return false;
            }
        }
        #endregion


        public string RequestDocument(string documentPath)
        {
                HttpWebResponse response;

                StringBuilder sb = new StringBuilder();
                var status = RequestDocumentFromUrl(documentPath, out response);
                if (status)
                {
                    // Gets the stream associated with the response.
                    Stream receiveStream = response.GetResponseStream();

                    Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
                    // Pipes the stream to a higher level stream reader with the required encoding format. 
                    StreamReader readStream = new StreamReader(receiveStream, encode);
                    Char[] read = new Char[256];
                    // Reads 256 characters at a time.    
                    int count = readStream.Read(read, 0, 256);

                    while (count > 0)
                    {
                        // Dumps the 256 characters on a string and displays the string to the console.
                        String str = new String(read, 0, count);
                        sb.Append(str);     //Append to string Builder
                        count = readStream.Read(read, 0, 256);
                    }
                    readStream.Close();
                    receiveStream.Close();

                }
                //Write to File.
                return sb.ToString();
        }

        /// <summary>
        /// Tries to request the URL: http://www.manupatra.com/NXT/gateway.dll/sc/supreme2001/sc2010/s100920.htm
        /// </summary>
        /// <param name="response">After the function has finished, will possibly contain the response to the request.</param>
        /// <returns>True if the request was successful; false otherwise.</returns>
        public bool RequestDocumentFromUrl(string documentUrl, out HttpWebResponse response)
        {
            response = null;

            try
            {
                //"http://localhost:49152/NXT/gateway.dll/Manupatra/sc/2001-2003SC/sc2010/s" + docNumber + ".htm"
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(documentUrl);
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; QS 4.2.4.0; QS 5.1.2.1; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; FDM; QS 4.2.4.0; QS 5.1.2.1; .NET4.0C; .NET4.0E; MS-RTC LM 8)";
                request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
                request.Headers.Set(HttpRequestHeader.AcceptLanguage, "en-us,en;q=0.5");
                request.Headers.Set(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
                request.Headers.Set(HttpRequestHeader.AcceptCharset, "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
                request.Headers.Add("Keep-Alive", "300");
                request.KeepAlive = true;
                request.Referer = "http://localhost:49152/NXT/gateway.dll/Manupatra/sc/2001-2003SC/sc2008/index.html?fn=document-frameset.htm&f=templates&uq=1$force=1778";
                //request.Headers.Set(HttpRequestHeader.Cookie, @"nxt/gateway.dll/uid=7DB6062A; nxt/gateway.dll/sid=7DB6062B");
                request.Headers.Set(HttpRequestHeader.Cookie, @"__utma=21732263.1795951994.1288761579.1289224314.1289368998.5; __utmz=21732263.1288761579.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utmb=21732263.1.10.1289368998; __utmc=21732263; nxt/gateway.dll/uid=59FFE516; ASP.NET_SessionId=suflbvntpfz41pm5hkt1ph34; ASPSESSIONIDSSCRQTDA=DLIHCFABMPLIBOJLHAEBNABI; NXT/gateway.dll/NPUSERNAME=User7; NXT/gateway.dll/NPPASSWORD=useraug16kgkd; NXT/gateway.dll/NPAC_CREDENTIALSPRESENT=TRUE; nxt/gateway.dll/sid=787BCBEC; nxt/gateway.dll/npac_ticket=%40lrSwi2cMbSUQF5y5jo%2FsDA%3D%3D%3AUser-NamecUser7%26expirationc63425068203; nxt/gateway.dll/npusername=; nxt/gateway.dll/nppassword=; nxt/gateway.dll/npac_credentialspresent=");

                //Get response to request.
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException e)
            {
                //ProtocolError indicates a valid HTTP response, but with a non-200 status code (e.g. 304 Not Modified, 404 Not Found)
                if (e.Status == WebExceptionStatus.ProtocolError) response = (HttpWebResponse)e.Response;
                else return false;
            }
            catch (Exception)
            {
                if (response != null) response.Close();
                return false;
            }

            return true;
        }
    }
}
